package com.itianyu.blog.web.controller;

import java.text.DateFormatSymbols;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.itianyu.blog.dao.beans.User;
import com.itianyu.blog.dao.interfaces.EntryInterface;
import com.itianyu.blog.dao.interfaces.TagInterface;
import com.itianyu.blog.util.SimpleBloggerConfig;

/**
 * 博文列表控制层
 * @author wumgji
 */
@Controller
@RequestMapping("/entries")
public class EntriesController {

	@Autowired
	private EntryInterface entryInterface;

	@Autowired
	private TagInterface tagInterface;

	@Autowired
	private SimpleBloggerConfig simpleBloggerConfig;

	// 显示博文列表的默认方法
	@RequestMapping(value = "", method = RequestMethod.GET)
	public ModelAndView listEntries() throws Exception {
		return new ModelAndView("redirect:/app/entries/1");
	}

	// 显示博文列表的分页方法
	@RequestMapping(value = "/{page}", method = RequestMethod.GET)
	public ModelAndView listEntries(@PathVariable("page") int page) throws Exception {
		// 计算已发布博文的总数
		int numresults = entryInterface.getEntryEntitiesCount(true);
		int lastpage = 1;
		ModelMap model = new ModelMap();

		if (numresults > 0) {
			if (numresults % simpleBloggerConfig.getEntriesPerPage() == 0) {
				lastpage = numresults / simpleBloggerConfig.getEntriesPerPage();
			} else {
				lastpage = (numresults / simpleBloggerConfig.getEntriesPerPage()) + 1;
			}

			if (page < 1) {
				page = 1;
			} else if (page > lastpage) {
				page = lastpage;
			}

			model.addAttribute("entries", entryInterface.findEntryEntities(page, simpleBloggerConfig.getEntriesPerPage(), true));
		}

		model.addAttribute("page", page);
		model.addAttribute("lastpage", lastpage);

		return new ModelAndView("entrylist", model);
	}
      
	// 显示文章列表
	@RequestMapping(value = "/entrymanagelist", method = RequestMethod.GET)
	public ModelAndView entrymanagelist() throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		User user = ((User) authentication.getPrincipal());
		return new ModelAndView("entrymanagelist", new ModelMap().addAttribute("entries", entryInterface.findEntryPageEntities(user)));
	}
	
	// 显示未发布博文列表的默认方法
	@RequestMapping(value = "/unpublished", method = RequestMethod.GET)
	public ModelAndView listUnpublishedEntries() throws Exception {
		return new ModelAndView("redirect:/app/entries/unpublished/1");
	}

	// 显示未发布博文列表的分页方法
	@RequestMapping(value = "/unpublished/{page}", method = RequestMethod.GET)
	public ModelAndView listUnpublishedEntries(@PathVariable("page") int page) throws Exception {
		// 计算未发布博文的总数
		int numresults = entryInterface.getEntryEntitiesCount(false);
		int lastpage = 1;
		ModelMap model = new ModelMap();

		if (numresults > 0) {
			if (numresults % simpleBloggerConfig.getEntriesPerPage() == 0) {
				lastpage = numresults / simpleBloggerConfig.getEntriesPerPage();
			} else {
				lastpage = (numresults / simpleBloggerConfig.getEntriesPerPage()) + 1;
			}

			if (page < 1) {
				page = 1;
			} else if (page > lastpage) {
				page = lastpage;
			}

			model.addAttribute("entries", entryInterface.findEntryEntities(page, simpleBloggerConfig.getEntriesPerPage(), false));
		}

		model.addAttribute("page", page);
		model.addAttribute("lastpage", lastpage);
		model.addAttribute("unpublished", true);

		return new ModelAndView("entrylist", model);
	}

	// 根据标签显示博文列表的默认方法
	@RequestMapping(value = "/bytag/{tagid}", method = RequestMethod.GET)
	public ModelAndView listEntriesByTag(@PathVariable("tagid") int tagid) throws Exception {
		return new ModelAndView("redirect:/app/entries/bytag/" + tagid + "/1");
	}

	// 根据标签显示博文列表的分页方法
	@RequestMapping(value = "/bytag/{tagid}/{page}", method = RequestMethod.GET)
	public ModelAndView listEntriesByTag(@PathVariable("tagid") int tagid, @PathVariable("page") int page) throws Exception {
		// 根据标签计算已发布博文的总数
		int numresults = entryInterface.getEntryEntitiesCountByTag(tagid);
		int lastpage = 1;
		ModelMap model = new ModelMap();

		if (numresults > 0) {
			if (numresults % simpleBloggerConfig.getEntriesPerPage() == 0) {
				lastpage = numresults / simpleBloggerConfig.getEntriesPerPage();
			} else {
				lastpage = (numresults / simpleBloggerConfig.getEntriesPerPage()) + 1;
			}

			if (page < 1) {
				page = 1;
			} else if (page > lastpage) {
				page = lastpage;
			}

			model.addAttribute("entries", entryInterface.findEntryEntitiesByTag(page, simpleBloggerConfig.getEntriesPerPage(), tagid));
		}

		model.addAttribute("page", page);
		model.addAttribute("lastpage", lastpage);
		model.addAttribute("tag", tagInterface.findTag(tagid));

		return new ModelAndView("entrylist", model);
	}

	// 根据日期显示博文列表的默认方法
	@RequestMapping(value = "/bydate/{year}/{month}", method = RequestMethod.GET)
	public ModelAndView listEntriesByDate(@PathVariable("year") int year, @PathVariable("month") int month) throws Exception {
		return new ModelAndView("redirect:/app/entries/bydate/" + year + "/" + month + "/1");
	}

	// 根据日期显示博文列表的分页方法
	@RequestMapping(value = "/bydate/{year}/{month}/{page}", method = RequestMethod.GET)
	public ModelAndView listEntriesByDate(@PathVariable("year") int year, @PathVariable("month") int month, @PathVariable("page") int page) throws Exception {
		// 根据日期计算已发布博文的总数（如果月mouth为0，将查询整年数据）
		int numresults = entryInterface.getEntryEntitiesCountByDate(year, month);
		int lastpage = 1;
		ModelMap model = new ModelMap();

		if (numresults > 0) {
			if (numresults % simpleBloggerConfig.getEntriesPerPage() == 0) {
				lastpage = numresults / simpleBloggerConfig.getEntriesPerPage();
			} else {
				lastpage = (numresults / simpleBloggerConfig.getEntriesPerPage()) + 1;
			}

			if (page < 1) {
				page = 1;
			} else if (page > lastpage) {
				page = lastpage;
			}

			model.addAttribute("entries", entryInterface.findEntryEntitiesByDate(page, simpleBloggerConfig.getEntriesPerPage(), year, month));
		}

		model.addAttribute("page", page);
		model.addAttribute("lastpage", lastpage);
		model.addAttribute("year", year);
		if (month > 0 & month <= 12) {
			model.addAttribute("month", month);
			model.addAttribute("month_name", new DateFormatSymbols().getMonths()[month - 1]);
			model.addAttribute("month_name", new DateFormatSymbols(Locale.ENGLISH).getMonths()[month - 1]);
		}

		return new ModelAndView("entrylist", model);
	}

	// 查询已发布的归档博文列表
	@RequestMapping(value = "/archives", method = RequestMethod.GET)
	@ResponseBody
	public List<String[]> tagEntryCount() throws Exception {
		return entryInterface.findArchivesEntries();
	}

}
